import axios from 'axios'
import config from './config'

export default function $axios (options, isFile = false) {
  return new Promise((resolve, reject) => {
    let headers = null
    if (!isFile) {
      headers = config.headers
    } else {
      headers = config.headersFile
    }
    const instance = axios.create({
      baseURL: config.baseUrl,
      headers: headers,
      timeout: config.timeout,
      withCredentials: config.withCredentials
    })
    instance.interceptors.request.use(
      config => {
        if (config.method === 'post') { }
        return config
      },
      error => {
        alert(error)
      }
    )

    instance.interceptors.response.use(
      response => {
        let data
        if (response.data === undefined) {
          data = JSON.parse(response.request.responseText)
        } else {
          data = response.data
        }
        return data
      },
      err => {
        return Promise.reject(err)
      }
    )

    instance(options).then(res => {
      resolve(res)
      return false
    }).catch(error => {
      reject(error)
    })
  })
}
